package core

import (
	"bytes"
	"fmt"
	"gitee.com/lvshicong/blog/global"
	"github.com/sirupsen/logrus"
	"os"
	"path"
	"time"
)

// 自定义日志相关功能实现
const (
	red = iota + 1
	green
	yellow
	blue
)

type MyFormatter struct {
	TimeFormat string
	Prefixe    string
}

func (m *MyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	var levelColor int
	//根据不同的level去展示颜色
	switch entry.Level {
	case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
		levelColor = red
	case logrus.WarnLevel:
		levelColor = yellow
	case logrus.DebugLevel, logrus.TraceLevel:
		levelColor = blue
	default:
		levelColor = green
	}

	var b *bytes.Buffer
	if entry.Buffer != nil {
		b = entry.Buffer
	} else {
		//buffer中不存在就初始化防止报错
		b = &bytes.Buffer{}
	}

	//函数名 日志显示效果: test/logger.Test1
	funcVal := entry.Caller.Function
	//显示文件绝对路径行号  日志显示效果:  D:/code/test/logger/自定义格式_test.go:59
	//fileval := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
	//显示文件相对路径和行号  日志显示效果:  自定义格式_test.go:63
	fileval := fmt.Sprintf("%s:%d", path.Base(entry.Caller.File), entry.Caller.Line)

	timestamp := entry.Time.Format(m.TimeFormat)
	fmt.Fprintf(b, "[%s] [%s] \033[3%dm[%s]\033[0m  %s %s %s\n", m.Prefixe, timestamp, levelColor, entry.Level, fileval, funcVal, entry.Message)
	return b.Bytes(), nil
}

// 日志分割相关功能
type FileDateHook struct {
	file     *os.File
	logPath  string
	fileDate string //判断日期切换目录
	appName  string
}

func (hook FileDateHook) Levels() []logrus.Level {
	return logrus.AllLevels
}
func (hook FileDateHook) Fire(entry *logrus.Entry) error {
	timer := entry.Time.Format("20060102")
	line, _ := entry.String()
	if hook.fileDate == timer {
		hook.file.Write([]byte(line))
		return nil
	}
	// 时间不等
	hook.file.Close()
	os.MkdirAll(fmt.Sprintf("%s/%s", hook.logPath, timer), os.ModePerm)
	filename := fmt.Sprintf("%s/%s/%s.log", hook.logPath, timer, hook.appName)

	hook.file, _ = os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
	hook.fileDate = timer
	hook.file.Write([]byte(line))
	return nil
}

func InitFile(logPath, appName string) {
	fileDate := time.Now().Format("20060102")
	//创建目录
	err := os.MkdirAll(fmt.Sprintf("%s/%s", logPath, fileDate), os.ModePerm)
	if err != nil {
		logrus.Error(err)
		return
	}

	filename := fmt.Sprintf("%s/%s/%s.log", logPath, fileDate, appName)
	file, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
	if err != nil {
		logrus.Error(err)
		return
	}
	fileHook := FileDateHook{file, logPath, fileDate, appName}
	logrus.AddHook(&fileHook)
}
func InitLogrus() {
	l := global.Config.Log
	logrus.SetOutput(os.Stdout)
	logrus.SetReportCaller(true)
	logrus.SetFormatter(&MyFormatter{"2006-01-02 15:04:05", l.App})
	logrus.SetLevel(logrus.DebugLevel)
	InitFile(l.Dir, l.App)
}
